package com.study.interceptors;

import com.study.pojo.Result;
import com.study.utils.JwtUtil;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 令牌验证
        String token = request.getHeader("Authorization");
        // 验证token
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 验证通过, 放行
            return true;
        } catch (Exception e) {
            // 验证失败, 不放行
            // 响应状态码为401
            response.setStatus(401);
            // 1. 不放行：设置响应内容
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8"); // 指定JSON格式和编码

            // 2. 构造返回给前端的JSON数据
            PrintWriter out = response.getWriter();

            String jsonResponse = "{\"code\":401,\"message\":\"token无效，请重新登录\",\"data\":null}";
            out.write(jsonResponse);

            // 3. 关闭输出流
            out.flush();
            out.close();
            return false;
        }
    }
}
